package org.springblade.common.utils.delayed;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.PropertyValueConst;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.thierrysquirrel.annotation.MessageListener;
import com.github.thierrysquirrel.annotation.RocketListener;
import com.google.protobuf.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.utils.message.MessageCenterUtils;
import org.springblade.common.utils.message.domain.MessageParam;
import org.springblade.common.utils.message.domain.SendRequest;
import org.springblade.core.tool.api.R;
import org.springblade.modules.admin.entity.*;
import org.springblade.modules.admin.enums.WxArriveStatusEnums;
import org.springblade.modules.admin.service.*;
import org.springblade.modules.admin.utils.MapUtil;
import org.springblade.modules.admin.vo.plan.PlanMaintainUserVO;
import org.springblade.modules.admin.vo.plan.wx.WxYjSendMsgVo;
import org.springblade.modules.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 维修-预警延迟队列监听
 *
 * @author zcc
 * @version 1.0
 * @date 2024/11/20 16:50
 */
@Slf4j
@RocketListener(groupID = "GID_WX_WARN", messageModel = PropertyValueConst.BROADCASTING)
public class WxDelayedReceive {

	@Autowired
	private IMaintainWxmsgTypeService maintainWxmsgTypeService;
	@Autowired
	private IUserTrajectoryService userTrajectoryService;
	@Autowired
	private IMaintainSignService maintainSignService;
	@Resource
	private Environment environment;
	@Autowired
	private MessageCenterUtils messageCenterUtils;

	@Autowired
	private IUserService userService;

	@Autowired
	private IMaintainPlanContentUserService planContentUserService;

	@Autowired
	private IMaintainPlanContentExtService maintainPlanContentExtService;


	@Autowired
	private IMaintainPlanContentService maintainPlanContentService;

	/**
	 * 发送维修预警消息
	 *
	 * @param message type 值说明
	 *                1:当指派人员10分钟后移动没有超过500米
	 *                2：当人员距离达到目的地剩余30%时提醒
	 *                3:超出预计时间未到达
	 */
	@MessageListener(topic = "wx_warn", tag = "wx_warn_msg")
	public void sendWxWarnMsg(String message) throws ServiceException {
		try {
			JSONObject jsonObject = JSONObject.parseObject(message);
			String curEnvironment = environment.getActiveProfiles()[0];
			String environment = Convert.toStr(jsonObject.get("environment"));
			if (!curEnvironment.equals(environment)) {
				return;
			}
			log.info("===============接收维修预警消息====================");
			log.info("接收时间:[{}],接受内容:[{}]", LocalDateTime.now(), message);
			JSONObject parseObject = JSON.parseObject(message);
			WxYjSendMsgVo wxYjSendMsgVo = JSON.parseObject(parseObject.get("wx_yj_msg").toString(), WxYjSendMsgVo.class);
			List<PlanMaintainUserVO> maintainUserList = wxYjSendMsgVo.getMaintainUserList();
			Integer type = wxYjSendMsgVo.getType();

			MaintainPlanContent maintainPlanContent = maintainPlanContentService.getById(wxYjSendMsgVo.getPlanId());
			MaintainWxmsgType detail = maintainWxmsgTypeService.detail(Convert.toStr(jsonObject.get("tenantId")));
			List<MaintainPlanContentUser> planContentUserList = planContentUserService.list(Wrappers.<MaintainPlanContentUser>lambdaQuery().eq(MaintainPlanContentUser::getPlanId, wxYjSendMsgVo.getPlanId()));
			if (type == 1) {
				log.info("10分钟后未出发-工单id=" + wxYjSendMsgVo.getPlanId() + "-时间:" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
				for (PlanMaintainUserVO planMaintainUserVO : maintainUserList) {
					for (MaintainPlanContentUser maintainPlanContentUser : planContentUserList) {
						if (maintainPlanContentUser.getUserId().equals(planMaintainUserVO.getMaintainUserId())) {
							if (maintainPlanContentUser.getWxArriveStatus() == null || maintainPlanContentUser.getWxArriveStatus() == 4 || maintainPlanContentUser.getWxArriveStatus() == 3 || maintainPlanContentUser.getWxArriveStatus() == 5) {
								UserTrajectory userTrajectory = userTrajectoryService.getOne(Wrappers.<UserTrajectory>lambdaQuery().between(UserTrajectory::getCreateTime, DateUtil.beginOfDay(new Date()), new Date()).eq(UserTrajectory::getUserId, planMaintainUserVO.getMaintainUserId()).eq(UserTrajectory::getTenantId, Convert.toStr(jsonObject.get("tenantId"))).orderByDesc(UserTrajectory::getCreateTime).last("limit 1"));
								int distance = MapUtil.getDistance(MapUtil.getLongitude(planMaintainUserVO.getLongitude()), MapUtil.getLatitude(planMaintainUserVO.getLatitude()), MapUtil.getLongitude(userTrajectory.getLongitude()), MapUtil.getLatitude(userTrajectory.getLatitude()));
								if (distance <= Convert.toInt(detail.getMoveKm().multiply(Convert.toBigDecimal(1000)))) {
									maintainPlanContentUser.setWxArriveStatus(WxArriveStatusEnums.NO_MOVE.getId());
									if (detail.getDisStartType() == 1) {
										try {
											String userAppPushId = userService.getUserAppPushId(maintainPlanContentUser.getUserId());
											if (StrUtil.isNotEmpty(userAppPushId)) {
												Map<String, String> contentMap = new HashMap<>(4);
												contentMap.put("min", detail.getMoveTime().toString());
												contentMap.put("sound", "not_move_music");
												contentMap.put("url", "/subpages/repair/repariDetail?planId=" + maintainPlanContent.getId() + "&elevatorId=" + maintainPlanContent.getElevatorId());
												SendRequest request = SendRequest.builder()
													.messageTemplateId("1859068395328442370")
													.messageParam(
														MessageParam.builder()
															.receiver(userAppPushId)
															.variables(contentMap)
															.callback(cn.hutool.core.map.MapUtil.of("planId", wxYjSendMsgVo.getPlanId()))
															.build()
													).build();
												R r = messageCenterUtils.sendMessage(request);
												log.info("10分钟后未出发发送-激光推送结果:" + JSON.toJSONString(r));
											}
										} catch (Exception e) {
											log.info("调用发送消息失败10.....");
											e.printStackTrace();
										}
									}
								}
							}
						}
					}
				}
			} else if (type == 2) {
				log.info("延迟队列更新即将超时达-工单id=" + wxYjSendMsgVo.getPlanId() + "-时间:" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
				for (PlanMaintainUserVO planMaintainUserVO : maintainUserList) {
					for (MaintainPlanContentUser maintainPlanContentUser : planContentUserList) {
						if (maintainPlanContentUser.getUserId().equals(planMaintainUserVO.getMaintainUserId())) {
							if (maintainPlanContentUser.getWxArriveStatus() == null || maintainPlanContentUser.getWxArriveStatus() == 4 || maintainPlanContentUser.getWxArriveStatus() == 3 || maintainPlanContentUser.getWxArriveStatus() == 5) {
								maintainPlanContentUser.setWxArriveStatus(WxArriveStatusEnums.ABOUT_ARRIVE_ON_TIME.getId());
							}
							if (detail.getAboutTimeoutType() == 1) {
								try {
									String userAppPushId = userService.getUserAppPushId(maintainPlanContentUser.getUserId());
									if (StrUtil.isNotEmpty(userAppPushId)) {
										Map<String, String> contentMap = new HashMap<>(4);
										long between = Convert.toLong(DateUtil.between(new Date(), wxYjSendMsgVo.getPlanArriveDate(), DateUnit.MINUTE), 2L);
										contentMap.put("min", Convert.toStr(between, "2"));
										contentMap.put("sound", "time_out_music");
										contentMap.put("url", "/subpages/repair/repariDetail?planId=" + maintainPlanContent.getId() + "&elevatorId=" + maintainPlanContent.getElevatorId());
										SendRequest request = SendRequest.builder()
											.messageTemplateId("1859411936432910337")
											.messageParam(
												MessageParam.builder()
													.receiver(userAppPushId)
													.variables(contentMap)
													.callback(cn.hutool.core.map.MapUtil.of("planId", wxYjSendMsgVo.getPlanId()))
													.build()
											).build();
										R sendMessage = messageCenterUtils.sendMessage(request);
										log.info("延迟队列更新即将超时达-激光推送结果:" + JSON.toJSONString(sendMessage));
									}
								} catch (Exception e) {
									log.info("调用发送消息失败....." + 1859411936432910337L);
									e.printStackTrace();
								}
							}

						}
					}
				}
			} else if (type == 3) {
				log.info("延迟队列更新....超时未达-工单id=" + wxYjSendMsgVo.getPlanId() + "-时间:" + DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
				MaintainPlanContentExt maintainPlanContentExt = maintainPlanContentExtService.getOne(Wrappers.<MaintainPlanContentExt>lambdaQuery().eq(MaintainPlanContentExt::getPlanId, wxYjSendMsgVo.getPlanId()));
				for (PlanMaintainUserVO planMaintainUserVO : maintainUserList) {
					for (MaintainPlanContentUser maintainPlanContentUser : planContentUserList) {
						if (maintainPlanContentUser.getUserId().equals(planMaintainUserVO.getMaintainUserId())) {
							MaintainSign maintainSign = maintainSignService.getOne(Wrappers.<MaintainSign>lambdaQuery().eq(MaintainSign::getPlanId, wxYjSendMsgVo.getPlanId()).eq(MaintainSign::getUserId, planMaintainUserVO.getMaintainUserId()).orderByAsc(MaintainSign::getCreateTime).last("limit 1"));
							if (maintainSign == null || maintainSign.getSignTime() == null) {
								if (maintainPlanContentExt.getWxArriveStatus() == null) {
									maintainPlanContentExt.setWxArriveStatus(WxArriveStatusEnums.DIS_ARRIVE_ON_TIME_NO_SIGN.getId());
								}
								maintainPlanContentUser.setWxArriveStatus(WxArriveStatusEnums.DIS_ARRIVE_ON_TIME_NO_SIGN.getId());
								try {
									String userAppPushId = userService.getUserAppPushId(maintainPlanContentUser.getUserId());
									if (StrUtil.isNotEmpty(userAppPushId)) {
										Map<String, String> contentMap = new HashMap<>(4);
										contentMap.put("url", "/subpages/repair/repariDetail?planId=" + maintainPlanContent.getId() + "&elevatorId=" + maintainPlanContent.getElevatorId());
										SendRequest request = SendRequest.builder()
											.messageTemplateId("1859413154890805249")
											.messageParam(
												MessageParam.builder()
													.receiver(userAppPushId)
													.variables(contentMap)
													.callback(cn.hutool.core.map.MapUtil.of("planId", wxYjSendMsgVo.getPlanId()))
													.build()
											).build();
										R r = messageCenterUtils.sendMessage(request);
										log.info("延迟队列更新超时未达-激光推送结果:" + JSON.toJSONString(r));
									}
								} catch (Exception e) {
									log.info("调用发送消息失败....." + 1859413154890805249L);
									e.printStackTrace();
								}
							}
						}
					}
				}
				maintainPlanContentExtService.updateById(maintainPlanContentExt);
			}
			planContentUserService.updateBatchById(planContentUserList);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
